package com.cspm.gen.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cspm.common.exception.CustomException;
import com.cspm.common.util.DateUtil;
import com.cspm.common.util.StringUtil;
import com.cspm.gen.entity.ColumnEntity;
import com.cspm.gen.entity.TableEntity;
import com.cspm.gen.enums.MysqlDataTypeEnum;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器   工具类
 * Created by CHQIU on 2017-04-15.
 */
public class GenUtils {
    public static List<String> getTemplates() {
        List<String> templates = new ArrayList<String>();
        templates.add("template/Entity.java.vm" );
        templates.add("template/Dao.java.vm" );
        templates.add("template/Mapper.xml.vm" );
        templates.add("template/Service.java.vm" );
        templates.add("template/ServiceImpl.java.vm" );
        templates.add("template/Controller.java.vm" );
       /* templates.add("template/list.html.vm");
        templates.add("template/list.js.vm");
        templates.add("template/menu.sql.vm");*/
        return templates;
    }


    public static void generatorCode(String codePackage, String author, Map<String, String> table, List<Map<String, String>> columns, ZipOutputStream zip) throws Exception {
        //配置信息
        Configuration config = getConfig();
        //表信息
        TableEntity tableEntity = new TableEntity();
        tableEntity.setTableName(table.get("tableName" ));
        tableEntity.setComments(table.get("tableComment" ));
        //表名转换成Java类名
        String className = tableToJava(tableEntity.getTableName(), config.getString("tablePrefix" ));
        tableEntity.setClassName(className);
        tableEntity.setClassname(StringUtils.uncapitalize(className));

        //列信息
        List<ColumnEntity> columsList = new ArrayList<ColumnEntity>();
        for (Map<String, String> column : columns) {
            ColumnEntity columnEntity = new ColumnEntity();
            //列名
            columnEntity.setColumnName(column.get("columnName" ));
            columnEntity.setDataType(column.get("dataType" ));
            columnEntity.setComments(column.get("columnComment" ));
            columnEntity.setExtra(column.get("extra" ));

            //列名转换成Java属性名
            String attrName = columnToJava(columnEntity.getColumnName());
            //大学开头属性
            columnEntity.setAttrName(attrName);
            //小写开头属性
            columnEntity.setAttrname(StringUtils.uncapitalize(attrName));

            //列的数据类型，转换成Java类型
            String attrType = config.getString(columnEntity.getDataType(), "unknowType" );
            columnEntity.setAttrType(attrType);
            columnEntity.setAttrType(getJavaType(columnEntity.getColumnName(), columnEntity.getDataType()));

            //是否主键
            if ("PRI".equalsIgnoreCase(column.get("columnKey" )) && tableEntity.getPk() == null) {
                tableEntity.setPk(columnEntity);
            }

            columsList.add(columnEntity);
        }
        tableEntity.setColumns(columsList);

        //没主键，则第一个字段为主键
        if (tableEntity.getPk() == null) {
            tableEntity.setPk(tableEntity.getColumns().get(0));
        }

        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader" );
        Velocity.init(prop);

        //封装模板数据
        Map<String, Object> map = new HashMap<>();
        map.put("tableName", tableEntity.getTableName());
        map.put("comments", tableEntity.getComments());
        map.put("pk", tableEntity.getPk());
        map.put("className", tableEntity.getClassName());
        map.put("classname", tableEntity.getClassname());
        map.put("columns", tableEntity.getColumns());
        if (StringUtil.isBlank(codePackage)) {
            codePackage = config.getString("package" );
        }
        map.put("package", codePackage);
        //URI修改为缩写
        map.put("pathName", getPathName(codePackage, tableEntity.getClassName()));
        if (StringUtil.isBlank(author)) {
            author = config.getString("author" );
        }
        map.put("author", author);
        map.put("datetime", DateUtil.dateToString(new Date()));
        VelocityContext context = new VelocityContext(map);

        //获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8" );
            tpl.merge(context, sw);

            try {
                //添加到zip
                zip.putNextEntry(new ZipEntry(getFileName(template, tableEntity.getClassName(), codePackage)));
                IOUtils.write(sw.toString(), zip, "UTF-8" );
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                throw new CustomException("渲染模板失败，表名：" + tableEntity.getTableName(), e);
            }
        }
    }

    /**
     * 根据数据库数据类型获取java对象类型
     *
     * @param columnName 字段名称
     * @param dataType   数据库数据类型
     * @return java对象类型
     */
    private static String getJavaType(String columnName, String dataType) {
        String javaType = "unknowType";
        MysqlDataTypeEnum dataTypeEnum = MysqlDataTypeEnum.getDataType(dataType);
        if (dataTypeEnum != null) {
            javaType = dataTypeEnum.getJavaType();
            //若字段是is_开头的表示为boolean类型的字段
            if (StringUtil.isNotBlank(columnName) && columnName.length() > 3 && columnName.substring(0, 3).equals("is_" )) {
                javaType = "Boolean";
            }
        }
        return javaType;
    }

    /**
     * 获取URL路径名称，用于生成Controller @RequestMapping
     *
     * @param codePackage 包名
     * @param classname   对象名称
     * @return
     */
    private static String getPathName(String codePackage, String classname) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("/" );
        buffer.append(codePackage.substring(codePackage.lastIndexOf('.') + 1, codePackage.lastIndexOf('.') + 2));
        buffer.append("/" );
        // 转为char数组
        char[] ch = classname.toCharArray();
        // 得到大写字母
        for (int i = 0; i < ch.length; i++) {
            if (ch[i] >= 'A' && ch[i] <= 'Z') {
                buffer.append(ch[i]);
            }
        }
        return buffer.toString().toLowerCase() + "c";
    }

    /**
     * 生成代码
     *
     * @param
     * @param columns
     * @param zip
     */
    public static void generatorCode(Map<String, String> table,
                                     List<Map<String, String>> columns, ZipOutputStream zip) throws Exception {
        generatorCode(null, null, table, columns, zip);
    }


    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        if (StringUtil.isNotBlank(columnName) && columnName.length() > 3 && columnName.substring(0, 3).equals("is_" )) {
            //TODO  is_
        }
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "" );
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String tablePrefix) {
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replace(tablePrefix, "" );
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties" );
        } catch (ConfigurationException e) {
            throw new CustomException("获取配置文件失败，", e);
        }
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, String className, String packageName) {
        String packagePath = "main" + File.separator + "java" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator;
        }
        if (template.contains("Controller.java.vm" )) {
            return packagePath + "controller" + File.separator + className + "Controller.java";
        } else if (template.contains("Service.java.vm" )) {
            return packagePath + "service" + File.separator + className + "Service.java";
        } else if (template.contains("ServiceImpl.java.vm" )) {
            return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
        } else if (template.contains("Entity.java.vm" )) {
            return packagePath + "entity" + File.separator + className + "Entity.java";
        } else if (template.contains("Dao.java.vm" )) {
            return packagePath + "dao" + File.separator + className + "Dao.java";
        } else if (template.contains("Mapper.xml.vm" )) {
            packagePath = "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + packageName.substring(packageName.lastIndexOf("." ) + 1);
            return packagePath + File.separator + className + "Mapper.xml";
        }
        return null;
    }

    public static void main(String[] args) {
        JSONArray jsonArray = new JSONArray();
        jsonArray.add("a" );
        jsonArray.add("b" );
        jsonArray.add("c" );
        String str = jsonArray.toJSONString();
        System.out.println(str);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("1", "A" );
        jsonObject.put("2", "B" );
        jsonObject.put("3", "A,C" );
        jsonObject.put("4", "D" );
        jsonObject.put("5", "这是答案" );
        str = jsonObject.toJSONString();
        System.out.println(str);
        System.out.println(StringUtil.match("", "is_deleted" ));

    }
}
